import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:lx_widgets_library/lx_widgets_library.dart';
import 'package:shared_preferences/shared_preferences.dart';

/// 展示用户协议和隐私政策的对话框
/// 用户首次进入应用时必须接受
class AgreementDialog extends StatefulWidget {
  /// 对话框标题
  final String title;

  /// 协议链接前的描述文本
  final String description;

  /// 用户协议标题文本
  final String userAgreementText;

  /// 隐私政策标题文本
  final String privacyPolicyText;

  /// and连接符号
  final String andText;

  /// 同意按钮文本
  final String agreeButtonText;

  /// 不同意按钮文本
  final String disagreeButtonText;

  /// 勾选项描述文本
  final String checkboxText;

  /// 用户不同意时的回调
  final VoidCallback? onDisagree;

  /// 用户同意时的回调
  final VoidCallback? onAgree;

  /// 用户协议超链接的回调
  final VoidCallback? userAgreementOnTap;

  /// 隐私政策超链接的回调
  final VoidCallback? privacyPolicyOnTap;

  /// 用于在shared preferences中存储协议状态的键
  final String prefsKey;

  const AgreementDialog({
    Key? key,
    this.title = 'User Agreement and Privacy Policy',
    this.description =
        'Please read and agree to the following terms before using the app:',
    this.userAgreementText = '《User Agreement》',
    this.privacyPolicyText = '《Privacy Policy》',
    this.andText = 'and',
    this.checkboxText = 'I agree to the terms and conditions',
    this.agreeButtonText = 'Agree',
    this.disagreeButtonText = 'Disagree',
    this.onDisagree,
    this.onAgree,
    this.userAgreementOnTap,
    this.privacyPolicyOnTap,
    this.prefsKey = 'has_agreed_to_terms',
  }) : super(key: key);

  /// 如果之前未显示过，则显示协议对话框。
  /// 如果用户已经同意或现在同意，则返回true。
  /// 如果用户不同意，则返回false。
  static Future<bool> showIfNeeded(
    BuildContext context, {
    required AgreementDialog dialog,
  }) async {
    final prefs = await SharedPreferences.getInstance();
    final hasAgreed = prefs.getBool(dialog.prefsKey) ?? false;

    if (hasAgreed) return true;
    if (!context.mounted) return false;
    final result = await showDialog<bool>(
      context: context,
      barrierDismissible: false,
      builder: (context) => dialog,
    );
    return result ?? false;
  }

  // 关闭对话框
  static dismiss(BuildContext context) {
    Navigator.of(context).pop(true);
  }

  @override
  State<AgreementDialog> createState() => _AgreementDialogState();
}

class _AgreementDialogState extends State<AgreementDialog>
    with TickerProviderStateMixin {
  bool _isChecked = false;
  late AnimationController _shakeController;
  late Animation<double> _shakeAnimation;

  @override
  void initState() {
    super.initState();
    _shakeController = AnimationController(
      duration: const Duration(milliseconds: 500),
      vsync: this,
    );
    _shakeAnimation = Tween<double>(
      begin: 0.0,
      end: 1.5, // 震动幅度
    ).animate(CurvedAnimation(
      parent: _shakeController,
      curve: Curves.elasticIn,
    ));
  }

  @override
  void dispose() {
    _shakeController.dispose();
    super.dispose();
  }

  /// 触发震动效果
  void _triggerShake() {
    _shakeController.forward().then((_) {
      _shakeController.reset();
    });
  }

  Future<void> _saveAgreement() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool(widget.prefsKey, true);
  }

  void _handleAgree() {
    _saveAgreement();
    Navigator.of(context).pop(true);
    if (widget.onAgree != null) {
      widget.onAgree!();
    }
  }

  void _handleDisagree() {
    Navigator.of(context).pop(false);
    if (widget.onDisagree != null) {
      widget.onDisagree!();
    }
  }

  void _openUserAgreement() {
    if (widget.userAgreementOnTap != null) {
      widget.userAgreementOnTap!();
    }
  }

  void _openPrivacyPolicy() {
    if (widget.privacyPolicyOnTap != null) {
      widget.privacyPolicyOnTap!();
    }
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: _buildPageHeadTitle(widget.title),
      content: SingleChildScrollView(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const SizedBox(height: 5),
            Text.rich(TextSpan(children: [
              TextSpan(
                text: '    ${widget.description}',
                style: const TextStyle(
                  fontSize: 16,
                ),
              ),
              TextSpan(
                  text: widget.userAgreementText,
                  style: TextStyle(
                    color: LxWidgetsLibraryService.to.colorType.color6,
                    fontSize: 16,
                  ),
                  recognizer: TapGestureRecognizer()
                    ..onTap = () {
                      _openUserAgreement();
                    }),
              TextSpan(
                text: widget.andText,
                style: const TextStyle(
                  fontSize: 16,
                ),
              ),
              TextSpan(
                  text: widget.privacyPolicyText,
                  style: TextStyle(
                    color: LxWidgetsLibraryService.to.colorType.color6,
                    fontSize: 16,
                  ),
                  recognizer: TapGestureRecognizer()
                    ..onTap = () {
                      _openPrivacyPolicy();
                    }),
            ])),
            const SizedBox(height: 16),
            AnimatedBuilder(
              animation: _shakeAnimation,
              builder: (context, child) {
                final shakeValue = _shakeAnimation.value;
                final offset =
                    (shakeValue * 10 * (1 - shakeValue)).clamp(-5.0, 5.0);
                return Transform.translate(
                  offset: Offset(offset, 0),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Transform.translate(
                        offset: const Offset(0, -2),
                        child: Checkbox(
                          fillColor: MaterialStateProperty.resolveWith<Color>(
                              (Set<MaterialState> states) {
                            if (states.contains(MaterialState.selected)) {
                              return LxWidgetsLibraryService
                                  .to.colorType.color6; // 选中时的背景色
                            }
                            return Colors.transparent; // 未选中时的背景色
                          }),
                          checkColor: Colors.white,
                          value: _isChecked,
                          onChanged: (value) {
                            setState(() {
                              _isChecked = value ?? false;
                            });
                          },
                        ),
                      ),
                      Expanded(
                        child: Padding(
                          padding: const EdgeInsets.only(top: 12),
                          child: Text(
                            widget.checkboxText,
                            softWrap: true,
                            overflow: TextOverflow.visible,
                          ),
                        ),
                      ),
                    ],
                  ),
                );
              },
            ),
            const SizedBox(height: 20),
            _buildRejectButton(context),
            const SizedBox(height: 5),
            _buildAcceptButton(context),
            const SizedBox(height: 10),
          ],
        ),
      ),
    );
  }

  /// 页头标题
  Widget _buildPageHeadTitle(String title) {
    return Container(
      margin: EdgeInsets.only(top: 16.w),
      child: Text(
        title,
        textAlign: TextAlign.center,
        style: const TextStyle(
          fontWeight: FontWeight.normal,
          fontSize: 20,
          height: 1,
        ),
      ),
    );
  }

  // 不同意
  Widget _buildRejectButton(BuildContext context) {
    return SizedBox(
      width: double.maxFinite,
      height: 44,
      child: LxButton(
          title: widget.disagreeButtonText,
          buttonTypeCustomColor: ButtonTypeColor()
            ..backgroundColor = Colors.transparent
            ..borderColor = Colors.transparent
            ..textColor = Colors.white.withOpacity(0.7),
          onTap: () {
            _handleDisagree();
          }),
    );
  }

  // 同意
  Widget _buildAcceptButton(BuildContext context) {
    return SizedBox(
      width: double.maxFinite,
      height: 44,
      child: LxButton(
          borderRadius: BorderRadius.circular(22),
          title: widget.agreeButtonText,
          onTap: () {
            if (_isChecked) {
              _handleAgree();
            } else {
              // 触发震动效果
              _triggerShake();
            }
          }),
    );
  }
}
